import { useState, useRef, useEffect } from 'react'
import { useDispatch } from 'react-redux'
import classNames from 'classnames'
import { todoDel, todoModifyStatus } from '../../store/actions/todo'

export default function TodoItem({ item }) {
  const dispatch = useDispatch()
  const inputRef = useRef(null)
  const handleDel = (id) => dispatch(todoDel(id))
  const handleChange = (id) => dispatch(todoModifyStatus(id))
  const [currentId, setCurrentId] = useState('')
  // !#1 建立变量
  const [currentName, setCurrentName] = useState('')
  const handleDblClick = (id) => {
    setCurrentId(id)
    // !#4 双击进行回填数据
    setCurrentName(item.name)
  }
  const handleBlur = () => {
    setCurrentId('')
    // !#5 把 currentName 置为初始状态
    setCurrentName('')
  }
  // !#3 输入的时候实时记录数据
  const handleNameChange = (e) => setCurrentName(e.target.value)
  useEffect(() => inputRef.current.focus(), [currentId])
  return (
    <li
      className={classNames({
        completed: item.done,
        editing: item.id === currentId,
      })}
    >
      <div className='view'>
        <input
          className='toggle'
          type='checkbox'
          checked={item.done}
          onChange={() => handleChange(item.id)}
        />
        <label onDoubleClick={() => handleDblClick(item.id)}>{item.name}</label>
        <button className='destroy' onClick={() => handleDel(item.id)}></button>
      </div>
      {/* //!#2 用 curretName 和 input 的 value 进行绑定 */}
      <input
        ref={inputRef}
        className='edit'
        value={currentName}
        onBlur={handleBlur}
        onChange={handleNameChange}
      />
    </li>
  )
}
